/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package maincz.tests.webapp.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Main
 */
public class PageCrawler {
    
    public static Document getNextPage(String url, Document doc, Map<String, String> cookies) {        
        
        Connection conn = Jsoup.connect(url);
        Elements els = doc.getElementById("aspnetForm").getElementsByTag("input");
        
        Map<String, String> params = new HashMap<String, String>();
        for (Element el: els) {
            String attribute = el.id();
            String value = el.attr("value");
            params.put(attribute, value);
        }
        
        params.put("__EVENTARGUMENT", "");
        params.put("__EVENTTARGET", "ctl00$ContentBody$pgrBottom$ctl08");
                
        conn.data(params);
        for (Entry<String, String> cookie: cookies.entrySet()) {
            conn.request().cookie(cookie.getKey(), cookie.getValue());
        }
        
        try {
            return conn.post();
        } catch (IOException ex) {
            return null;
        }
    }
    
    public static Integer getPageCount(Document doc) {
        
        String str = doc.getElementsByClass("PageBuilderWidget").first().getElementsByTag("span").first()
                            .getElementsByTag("b").get(2).text();
        return Integer.parseInt(str);
    }
    
    public static Integer getPageNumber(Document doc) {
        
        String str = doc.getElementsByClass("PageBuilderWidget").first().getElementsByTag("span").first()
                            .getElementsByTag("b").get(1).text();
        return Integer.parseInt(str);
    }    
}
